import SystemMessageDom from '@/base/systemMessage/systemMessage.vue'
import { createApp } from 'vue'
import type { ComponentPublicInstance } from 'vue'
import type { Emitter } from 'mitt'
import type { App } from 'vue'

export type IMessageType = 'warning' | 'info'

export type EmitterType = {
  close: void
}

export interface SystemMessageProps {
  type: IMessageType
  title: string
  content: string
}

interface ISystemMessageComponent extends ComponentPublicInstance {
  messageMitt: Emitter<EmitterType>
}

class SystemMessageInstance {
  private readonly props: Partial<SystemMessageProps>

  constructor(props: Partial<SystemMessageProps>) {
    this.props = props
    this._initMessage()
  }

  private _initMessage() {
    const messageWrapper = document.createElement('div')
    messageWrapper.className = 'system-message-wrapper'
    document.body.appendChild(messageWrapper)
    const messageApp = createApp(SystemMessageDom, this.props) as App
    const messageAppInstance = messageApp.mount(messageWrapper) as ISystemMessageComponent
    messageAppInstance.messageMitt &&
      messageAppInstance.messageMitt.on('close', () => {
        messageApp.unmount()
        messageWrapper && messageWrapper.remove()
        messageAppInstance.messageMitt && messageAppInstance.messageMitt.off('close')
      })
  }
}

export const systemMessage = (props: Partial<SystemMessageProps>) => new SystemMessageInstance(props)
systemMessage.warning = (title: string, content?: string) => {
  return new SystemMessageInstance({ title, content, type: 'warning' })
}
